<template>
  <div
    class="el-message-box"
    :style="cssStyle"
    :class="`el-message--${props.type}`"
    ref="messageRef"
    v-show="visible"
  >
    <div class="message-box-title">
      <span
        >{{ height }} {{ lastOffset }} {{ topOffset }} {{ bottomOffset }}</span
      >
      <span>{{ message }}</span>
    </div>
    <div v-if="showClose" @click="visible = false">×</div>
  </div>
</template>

<script setup lang="ts">
import type { MessageProps } from "./types";
import { getLastBottomOffset } from "./method";

const props = withDefaults(defineProps<MessageProps>(), {
  message: "消息",
  duration: 3000,
  showClose: false,
  type: "info",
  offset: 20,
});

// 1.计算div的高度
const height = ref(0);
const messageRef = ref<HTMLElement>();

// 2.获取上一个组件实例的最下面的坐标数字
const lastOffset = computed(() => getLastBottomOffset(props.id));

// 3.获取该元素的top计算值
const topOffset = computed(() => lastOffset.value + props.offset);

// 4.该元素微下一个元素预留的offset, 也就是该元素的bottom
const bottomOffset = computed(() => height.value + topOffset.value);

const cssStyle = computed(() => ({
  top: `${topOffset.value}px`,
}));

const visible = ref(false);

function startTimer() {
  if (props.duration === 0) return;
  setTimeout(() => {
    visible.value = false;
  }, props.duration);
}

onMounted(async () => {
  visible.value = true;
  await nextTick();
  height.value = messageRef.value!.getBoundingClientRect().height;
  startTimer();
});

watch(visible, (newVal) => {
  if (!newVal) {
    props.onDestroy();
  }
});

defineExpose({
  bottomOffset,
});
</script>

<style scoped lang="scss"></style>
